from crawlers.utils import fetch_json_data
from crawlers.constants import XFZ_BASE_URL, XFZ_HOT_REPORTS_URL, XFZ_NEW_REPORTS_URL, REQUEST_HEADERS

def get_articles_from_xfz(type):
    """从小饭桌获取最新文章

    Parameters:
        type: 报告类型，'new'或'hot'
    
    Returns:
        文章列表，每个文章包含序号、标题、链接、时间和作者信息、作者链接、文章类型、简介、图片链接和关键词、关键词链接
    """
    if type == 'new':
        url = XFZ_NEW_REPORTS_URL
    else:
        url = XFZ_HOT_REPORTS_URL
    json_data = fetch_json_data(url, REQUEST_HEADERS)
    reports = []
    for index, item in enumerate(json_data):
        reports_info = {}
        reports_info['order'] = index + 1 
        reports_info['title'] = item['title']
        reports_info['url'] = f"{XFZ_BASE_URL}/post/{item['uid']}.html"
        reports_info['created_at'] = item['time']
        reports_info['article_type'] = item['article_type']
        reports_info['intro'] = item['intro']
        reports_info['photo_url'] = item['photo']
        reports_info['authors'] = []
        for author in item['author']['authors']:
          new_author = {}
          new_author['name'] = author['name']
          new_author['url'] = f"{XFZ_BASE_URL}/author/{author['author_id']}.html"
          reports_info['authors'].append(new_author)
        reports_info['keywords'] = []
        for keyword in item['keywords']:
          new_keyword = {}
          new_keyword['name'] = keyword
          new_keyword['url'] = f"{XFZ_BASE_URL}/post/search/?keyword={keyword}"
          reports_info['keywords'].append(new_keyword)
        reports.append(reports_info)
    return reports